package wsz.rocketMq.conf;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;
import wsz.rocketMq.entity.Order;
import wsz.rocketMq.service.OrderService;
import wsz.rocketMq.util.Constants;

import java.sql.Timestamp;
import java.util.Collections;

/**
 * 消费者监听
 * @author wsz
 * @date 2022/3/2 10:51
 **/
@Slf4j
@Component
@RocketMQMessageListener(topic = "topic_phone", consumerGroup = "consumer_group_phone")
public class PhoneConsumer implements RocketMQListener<MqMessage> {

    @Autowired
    private OrderService orderService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void onMessage(MqMessage message) {
        log.info("消费者接受异步订单信息：{}",message.toString());

        // 1.再次判断库存并减库存
        boolean luaNumber = luaNumber();
        if (!luaNumber) return;

        // 2.根据消息生产订单
        Order newOrder = new Order();
        newOrder.setStatus(Constants.PAY_NO);
        newOrder.setRelateId(message.getPhoneId());
        newOrder.setCreateTime(new Timestamp(System.currentTimeMillis()));
        orderService.save(newOrder);
        log.info("消费者新增订单：{}", newOrder);
    }

    /**
     * lua脚本原子判断剩余库存并减库存
     * @return
     */
    private boolean luaNumber() {
        String script = "local value = redis.call('get', KEYS[1]);" +
                "if tonumber(value) < 1 then return 0;" +
                "else redis.call('incrby', KEYS[1], -1); return 1;" +
                "end";
        Long execute = redisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Collections.singletonList(Constants.KILL_PHONE_KEY));
        return execute == 1L;
    }
}
